package Leo.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;

@Component
public class BaseWebsocketHandler implements WebSocketHandler {

    private HashMap<String,WebSocketSession> sessionMap = new HashMap<>();

    /**
     * 建立连接后
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String sessionId = webSocketSession.getId();
        sessionMap.put(sessionId,webSocketSession);
        System.out.println(sessionId + "加入成功");
    }

    /**
     * 消息处理，在客户端通过Websocket API发送的消息会经过这里，然后进行相应的处理
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        System.out.println("发消息");
        if(webSocketSession.isOpen()){
            if(webSocketMessage instanceof TextMessage){
                TextMessage textMessage = (TextMessage)webSocketMessage;
                String content = new String(textMessage.asBytes());
                webSocketSession.sendMessage(new TextMessage("你发送的消息是："+content));
                //此处理应实现的内容是，通过content，获取发送目标对象，在map中找到该session，并发过去
                String[] split = content.split(",");
                if(split.length > 1){
                    WebSocketSession targetSession = sessionMap.get(split[0]);
                    if(targetSession != null && targetSession.isOpen()){
                        targetSession.sendMessage(new TextMessage(content.substring(split[0].length()+1)));
                    }
                }
            }
        }
    }

    /**
     * 消息传输错误处理
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        System.out.println("Socket会话已经移除:用户ID");
    }

    /**
     * 关闭连接后
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        System.out.println("Socket会话已经关闭:");
        sessionMap.put(webSocketSession.getId(),null);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
